package inbound_invoice

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type InboundInvoiceListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewInboundInvoiceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InboundInvoiceListLogic {
	return &InboundInvoiceListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InboundInvoiceListLogic) InboundInvoiceList(req *types.InboundInvoiceListRequest) (resp *types.InboundInvoiceListResponse, err error) {
	resp = new(types.InboundInvoiceListResponse)
	resp.Data.List = make([]types.InboundInvoice, 0)

	var querys []string
	if req.SupplierId > 0 {
		var supplier *model.Supplier
		supplier, err = l.svcCtx.SupplierModel.FindOne(l.ctx, req.SupplierId)
		switch err {
		case nil:
			querys = append(querys, fmt.Sprintf("supplier_id = %d", supplier.Id))
		case model.ErrNotFound:
			fmt.Printf("[Error]供货商[%d]不存在\n", req.SupplierId)
			resp.Code = http.StatusNoContent
			resp.Msg = "供货商不存在"
			return resp, nil
		default:
			fmt.Printf("[Error]模糊查询供货商:%s\n", err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}
	}

	var query string
	if len(querys) > 0 {
		query = " where " + strings.Join(querys, " and ")
	}

	query += " order by date desc "

	queryLimit := query + fmt.Sprintf(" limit %d,%d", (req.Page-1)*req.Size, req.Size)

	//1.查询总数
	total, err := l.svcCtx.InboundInvoiceModel.Count(l.ctx, query)
	switch err {
	case nil:
	case model.ErrNotFound:
		resp.Code = http.StatusNoContent
		resp.Msg = "成功"
		return resp, nil
	default:
		fmt.Printf("[Error]查询供货商已开发票:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	if total == 0 {
		resp.Code = http.StatusOK
		resp.Msg = "成功"
		return resp, nil
	}
	resp.Data.Total = total

	//2.查询分页
	invoices, err := l.svcCtx.InboundInvoiceModel.FindByPage(l.ctx, queryLimit)
	switch err {
	case nil:
	case model.ErrNotFound:
		resp.Code = http.StatusNoContent
		resp.Msg = "成功"
		return resp, nil
	default:
		fmt.Printf("[Error]查询供货商已开发票分页:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	for _, one := range invoices {
		resp.Data.List = append(resp.Data.List, types.InboundInvoice{
			Id:           one.Id,
			SupplierId:   one.SupplierId,
			SupplierName: one.SupplierName,
			Total:        one.Total,
			Tax:          one.Tax,
			Date:         one.Date,
			CreatedAt:    one.CreatedAt.Unix(),
			UpdatedAt:    one.UpdatedAt.Unix(),
		})
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return
}
